const { axios } = require('../../utils/http')

Page({
  data: {
    socketTask: null,
    userInfo: null,
    userMessageList: [],
    chatMessage: ''
  },
  onLoad({ toUser }) {
    toUser && this.setData({ toUser })
  },
  onShow() {
    this.getChatList()
    this.startConnectSocketTask()
  },
  onUnload() {
    this.closeConnect()
  },
  getChatList() {
    axios.get('/chatRoom/search').then(res => {
      res.data.error === -1 &&
        this.setData(
          {
            userMessageList: res.data.data
          },
          () => {
            this.scrollBottom('.chatroom')
          }
        )
    })
  },
  scrollBottom(selector, time = 0) {
    const query = wx.createSelectorQuery()
    const domArr = query.select(selector).boundingClientRect()
    query.exec(res => {
      wx.pageScrollTo({
        scrollTop: res[0].height,
        duration: time
      })
    })
  },
  startConnectSocketTask() {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({
      userInfo
    })
    const socketTask = wx.connectSocket({
      url: `wss://www.ttzxh.icu/api/socketRoom/${userInfo.id}`,
      success: () => {
        console.log('链接成功')
        this.setData({
          socketTask
        })
      },
      fail: this.fail
    })
    if (socketTask) {
      this.setData({
        socketTask
      })
      socketTask.onMessage(res => {
        console.log(res.data)
        const chatInfo = JSON.parse(res.data)
        this.setData(
          {
            userMessageList: [...this.data.userMessageList, chatInfo]
          },
          () => this.scrollBottom('.chatroom', 100)
        )
      })
    }
  },
  sendMessage(type = { type: 'chat', message: '' }) {
    if (!this.data.socketTask) {
      console.log('链接失败')
      return
    }
    const message = type.message || this.data.chatMessage
    if (!message.trim()) {
      return
    }
    const messageInfo = {
      message,
      userId: this.data.userInfo.id,
      type: 'chat',
      realname: this.data.userInfo.realname,
      avatar: this.data.userInfo.avatar
    }
    this.data.socketTask.send({
      data: JSON.stringify(messageInfo),
      fail: this.fail,
      success: () => {
        this.setData({
          chatMessage: ''
        })
      }
    })
  },
  closeConnect() {
    if (!this.data.socketTask) {
      console.log('链接失败')
      return
    }
    this.data.socketTask.close()
  },
  fail() {
    console.log('链接失败')
    this.setData({
      socketTask: null
    })
  }
})
